﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using iTextSharp.text.pdf;
using System.Drawing;
using System.Drawing.Imaging;

namespace pdf_extract_image
{
    public class PdfExtracter
    {
        public static IEnumerable<Image> ExtractImages(FileInfo pdf)
        {
            var images = new List<Image>();
            try
            {
                var pages = GetPages(pdf);
                foreach (var page in pages)
                {
                    PdfDictionary resource = (PdfDictionary)PdfReader.GetPdfObject(page.Get(PdfName.RESOURCES));
                    PdfDictionary xobj = (PdfDictionary)PdfReader.GetPdfObject(resource.Get(PdfName.XOBJECT));

                    if (xobj == null) continue;

                    foreach (PdfName name in xobj.Keys)
                    {
                        PdfObject pdfObj = xobj.Get(name);
                        if (!pdfObj.IsIndirect()) continue;

                        PdfDictionary tg = (PdfDictionary)PdfReader.GetPdfObject(pdfObj);
                        PdfName type = (PdfName)PdfReader.GetPdfObject(tg.Get(PdfName.SUBTYPE));
                        if (!(PdfName.IMAGE.Equals(type))) continue;

                        var pdfStream = (PdfStream)tg;

                        var bytes = PdfReader.GetStreamBytesRaw((PRStream)pdfStream);
                        if (bytes == null) continue;
                        try
                        {
                            var memStream = new MemoryStream(bytes);
                            memStream.Position = 0;
                            images.Add(Image.FromStream(memStream));
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error converting pdf object to image. \n" + ex.ToString());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error extracting Pdf Objects. \n" + ex.ToString());
            }
            return images;
        }

        private static IEnumerable<PdfDictionary> GetPages(FileInfo pdf)
        {
            var raf = new RandomAccessFileOrArray(pdf.FullName);
            using (var reader = new PdfReader(raf, null))
            {
                for (int pageNumber = 1; pageNumber <= reader.NumberOfPages; pageNumber++)
                {
                    yield return reader.GetPageN(pageNumber);
                }
            }
        }
    }
}
